package com.zshan.clinic.mini.config;

import com.zshan.clinic.common.util.date.DateTimeUtils;
import com.zshan.clinic.mini.interceptor.SessionCheckInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 请求拦截器
 * @author lichen
 */
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {  // 直接实现接口

    @Bean
    public SessionCheckInterceptor sessionCheckInterceptor() {
        return new SessionCheckInterceptor();
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(String.class, LocalDate.class, source -> {
            if (!StringUtils.hasText(source)) {
                return null;
            }
            try {
                // 标准格式
                return LocalDate.parse(source);
            } catch (Exception e1) {
                try {
                    // 兼容 yyyyMMdd 格式
                    return LocalDate.parse(source, DateTimeFormatter.ofPattern(DateTimeUtils.YYYYMMDD));
                } catch (Exception exception) {
                    log.error("日期解析错误:{}",source);
                    return null;
                }
            }
        });
    }
    /**
     * 增加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionCheckInterceptor())
                .addPathPatterns("/**");
    }
}

